package org.ben.birthday.twentybirthday.controller.travel.backgroundPage;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.ben.birthday.twentybirthday.entity.User;
import org.ben.birthday.twentybirthday.utils.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Ben
 * @Date: 2019/7/25 8:03
 */
@RestController
@RequestMapping("/Administrator")
@Api(tags = "管理员接口", value = "AdministratorController")
public class AdministratorController extends BaseController {


    private static final Logger logger = LoggerFactory.getLogger(AdministratorController.class);

    /**
     * 管理员增加用户信息Controller
     * @param user
     * @param result
     * @return ModelAndView
     */
    @RequestMapping(value = "/insertUser",method = RequestMethod.POST)
    @ApiOperation(value = "管理员添加用户",notes = "用户不能为空", httpMethod = "POST", response = ModelAndView.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userName",
                    value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "password",
                    value = "密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "phoneNumber",
                    value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "email",
                    value = "邮箱", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "encryptedProblem",
                    value = "密保问题", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "encryptedAnswer",
                    value = "密保答案", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "level",
                    value = "用户等级", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "userType",
                    value = "用户类别", required = true, dataType = "String"),
    })
    public ModelAndView insertUserController(@Valid User user, BindingResult result) {
        ModelAndView modelAndView = new ModelAndView();
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            List<FieldError> errors = result.getFieldErrors();
            logger.error("添加失败！");
            for (FieldError fieldError : errors) {
                logger.error("错误的字段名：" + fieldError.getField());
                logger.error("错误信息：" + fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            modelAndView.addObject("errorFields",map);
            modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
            return modelAndView;
        }
    boolean judgment=iAdministratorService.insertUserService(user);
        if (judgment){
            modelAndView.addObject("success","添加成功");
            modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
            return modelAndView;
        }else {
            modelAndView.addObject("error","添加失败");
            modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
            return modelAndView;
        }
    }


    /**88
     * 管理员删除用户信息Controller
     * @param userId
     * @param userName
     * @return ModelAndView
     */
    @RequestMapping(value = "/deleteUser",method = RequestMethod.DELETE)
    @ApiOperation(value = "管理员删除用户",notes = "用户不能为空", httpMethod = "DELETE", response = ModelAndView.class)
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query", name = "userId",
                value = "用户id", required = true, dataType = "Integer"),
        @ApiImplicitParam(paramType = "query", name = "userName",
                value = "用户名", required = true, dataType = "String"),
})
public ModelAndView deleteUserController(@Param("userId") String userId,@Param("userName") String userName){
    ModelAndView modelAndView = new ModelAndView();
   if (userId==null||userName==null){
       logger.error("用户id或者用户名为空，删除失败");
        modelAndView.addObject("error","用户id或者用户名为空，删除失败");
        modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
        return modelAndView;
    }else {
       Integer userIdInteger=Integer.parseInt(userId);
   boolean judgment=iAdministratorService.deleteUserService(userIdInteger,userName);
    if (judgment){
        modelAndView.addObject("success","删除成功");
        modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
        return modelAndView;
    }else {
        modelAndView.addObject("error","删除失败");
        modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
        return modelAndView;
    }
    }
}

    /**
     * 管理员更改用户信息Controller
     * @param user
     * @param result
     * @return ModelAndView
     */
    @RequestMapping(value = "/updateUser",method = RequestMethod.PUT)
    @ApiOperation(value = "管理员更改用户",notes = "用户不能为空", httpMethod = "PUT", response = ModelAndView.class)
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query", name = "userName",
                value = "用户名", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "password",
                value = "密码", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "phoneNumber",
                value = "手机号", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "email",
                value = "邮箱", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "encryptedProblem",
                value = "密保问题", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "encryptedAnswer",
                value = "密保答案", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "level",
                value = "用户等级", required = true, dataType = "Integer"),
        @ApiImplicitParam(paramType = "query", name = "userType",
                value = "用户类别", required = true, dataType = "String"),
})
public ModelAndView updateUserController(@Valid User user,BindingResult result) {
    ModelAndView modelAndView = new ModelAndView();
    if (result.hasErrors()) {
        Map<String, Object> map = new HashMap<>();
        List<FieldError> errors = result.getFieldErrors();
        logger.error("更改失败！");
        for (FieldError fieldError : errors) {
            logger.error("错误的字段名：" + fieldError.getField());
            logger.error("错误信息：" + fieldError.getDefaultMessage());
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        modelAndView.addObject("errorFields", map);
        modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
        return modelAndView;
    } else {
        boolean judgment = iAdministratorService.updateUserService(user);
        if (judgment) {
            modelAndView.addObject("success", "更改成功");
            modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
            return modelAndView;
        } else {
            modelAndView.addObject("error", "更改失败");
            modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
            return modelAndView;
        }
    }
}



    /**
     * 管理员分页查询用户信息Controller
     * @param pageNumber
     * @param pageSize
     * @return ModelAndView
     */
    @RequestMapping(value = "/selectUser",method = RequestMethod.GET)
    @ApiOperation(value = "管理员查询用户数据",notes = "查询所有用户数据", httpMethod = "GET", response = ModelAndView.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNumber",
                    value = "当前页", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageSize",
                    value = "每页数据", required = true, dataType = "String"), })
    public ModelAndView selectUserController(@Param("pageNumber") String pageNumber,@Param("pageSize") String pageSize){
        ModelAndView modelAndView=new ModelAndView();
        Integer pageNumberInteger=Integer.parseInt(pageNumber);
        Integer pageSizeInteger=Integer.parseInt(pageSize);
        Page<User> userPage=iAdministratorService.selectUser(pageNumberInteger-1,pageSizeInteger);
        modelAndView.addObject("userPage",userPage);
        modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
        return modelAndView;
    }
}
